package com.shop.order.server.controller;

import com.shop.order.server.service.OrderService;
import com.shop.order.server.util.ResultUtil;
import com.shop.order.server.vo.OrderCreateVo;
import com.shop.order.server.vo.ResultVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

/**
 * Created with IntelliJ IDEA.
 * User: dpengpeng
 * Date: 2018/5/19
 * Time: 11:39 Description:
 */
@RestController
@RequestMapping("order")
public class OrderController {

    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public ResultVo create(@Valid @RequestBody OrderCreateVo vo, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            throw new RuntimeException(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        String orderId = orderService.create(vo);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        return ResultUtil.success(map);

    }

    @PostMapping("/finish")
    public ResultVo finish(@RequestParam("orderId") String orderId) {
        orderService.finish(orderId);
        return ResultUtil.success(null);
    }

}
